# -*- coding: utf-8 -*-
# standard
import os
import sys

# third
from fastapi import Request
from fastapi import Header
from fastapi.exceptions import HTTPException

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from toolbox.common_tools import get_fastapi_real_ip
from db import *


"""
@Title:   
@File: base_model.py
@Author: walle 2024年12日08日 10时25分31秒
@Version: 1.0.0
@Desc: 
"""

TASK_AUTHORIZATION = "Bearer 5a76227de2252dfaaf787a8e4d48db04"
ALLOWED_IPS = ['116.226.59.213', '127.0.0.1']


async def check_instruction_authorization(request: Request, authorization: str | None = Header(None, description="请求头")) -> Optional[str]:
    """
    检查微服务发送请求时授权 失败会抛出异常，否则会返回请求头或者None(没有请求头的情况)
    注意，这个函数在不同的视图的实现不同
    :return: _description_
    """
    if authorization != TASK_AUTHORIZATION and get_fastapi_real_ip(request) not in ALLOWED_IPS:
        logger.error(f"请求头验证失败: authorization = {authorization}")
        raise HTTPException(status_code=404)
    return authorization


def get_module_title(module: object) -> str:
    """
    获取模块标题
    :param module: _description_
    :return: _description_
    """
    for line in inspect.getsourcelines(module)[0]:
        line = line.strip()
        if line.startswith("@Title:"):
            parts = line.split(":", 1)
            return parts[-1]
        

class CommonDeleteMicServiceParams(BaseModel):
    """适用微服务的通用删除参数"""
    ids: List[int] = Field(..., description="要删除的id列表")
    customer_id: int | None = Field(None, description="客户id")


class MyEnum(Enum):
    # 枚举基类
    @classmethod
    def get_selector(cls) -> list:
        """
        返回一个选择器
        """
        return [{"name": key.value, "value": key.value} for key in cls]
    

class EventPriority(MyEnum):
    """
    事件优先级
    """
    WARNING: str = "预警"
    ALERT: str = "告警"
    WIRED_BROADBAND_DISCONNECT: str = "有线宽带断网"

    
class NotificationSource(MyEnum):
    """
    通知源头
    """
    E_SENSOR_OFFLINE: str = "能耗传感器离线"
    E_SENSOR_THRESHOLD: str = "能耗传感器值异常"
    T_SENSOR_OFFLINE: str = "温度传感器离线"
    T_SENSOR_THRESHOLD: str = "温度传感器值异常"
    GATEWAY_OFFLINE: str = "网关离线"  # 所有的源自网关的通知，都使用这个， 历史原因
    LAN_OFFLINE: str = "内网节点离线"


class MicServiceSource(MyEnum):
    """
    微服务来源
    """
    IOT: str = "iot"
    GATEWAY: str = "gateway"
    LAN: str = "lan"

    @classmethod
    def get_instance_from_notification_source(cls, source: NotificationSource):
        """
        获取来源
        :param source:
        :return:
        """
        if source == NotificationSource.GATEWAY_OFFLINE:
            return cls.GATEWAY
        elif source == NotificationSource.LAN_OFFLINE:
            return cls.LAN
        else:
            return cls.IOT
    
    def get_authorization(self) -> str:
        """
        获取授权
        """
        if self == MicServiceSource.IOT:
            return IOT_AUTH
        elif self == MicServiceSource.GATEWAY:
            return GATEWAY_AUTH
        else:
            return LAN_AUTH
        
    def get_mic_service_host(self) -> str:
        """
        获取微服务主机
        """
        if self == MicServiceSource.IOT:
            return IOT_URL
        elif self == MicServiceSource.GATEWAY:
            return GATEWAY_URL
        else:
            return LAN_URL
        
    def get_raw_obj_query_path(self) -> str:
        """
        获取原始对象查询路径 / 开头
        """
        if self == MicServiceSource.IOT:
            return "/iot/sensor/status/get_by_id"  # 传感器的查询路径
        elif self == MicServiceSource.GATEWAY:
            return "/v1/zabbix/gateway/status/get_by_id"  # 网关的查询路径
        else:
            return "/ops/node/status"  # 内网设备的查询路径
        
    def get_raw_obj_query_url(self) -> str:
        """
        获取原始对象查询URL
        """
        return f"{self.get_mic_service_host()}{self.get_raw_obj_query_path()}"
    

class NotificationMethodName(MyEnum):
    """
    通知方法名
    """
    FEISHU: str = "飞书"
    DD_GROUP: str = "钉钉群"
    WORK_WX_GROUP: str = "企业微信群"
    SMS: str = "短信"
    TEL: str = "电话语音"
    WX_MES: str = "微信模板消息"


if __name__ == '__main__':
    pass